#!/bin/bash

# ============================================
# 系统配置验证脚本 (System Configuration Verification Script)
# 功能：全面验证Ansible项目结构和系统环境的完整性
# 作者：系统管理员
# 版本：1.0
# 日期：2024-01-01
# 
# 脚本用途：
#   - 验证Ansible项目目录结构的完整性
#   - 检查系统必备软件和命令的可用性
#   - 测试Ansible连接性和playbook语法
#   - 执行各个模块的专项验证（安全、备份等）
#   - 生成详细的系统验证报告
#   - 提供系统状态评估和改进建议
# 
# 此脚本用于验证整体系统配置，包括安全和备份设置
# This script verifies the overall system configuration including security and backup
# ============================================

# ============================================
# 输出颜色定义 - 用于美化输出显示
# Colors for output - Used to beautify output display
# 定义各种颜色代码，提升脚本输出的可读性和用户体验
# 使用ANSI转义序列实现终端颜色显示
# ============================================
RED='\033[0;31m'     # 红色 - 用于失败状态和错误信息显示
GREEN='\033[0;32m'   # 绿色 - 用于成功状态和通过信息显示
YELLOW='\033[1;33m'  # 黄色 - 用于警告状态和需要注意的项目
BLUE='\033[0;34m'    # 蓝色 - 用于信息状态和一般提示信息
PURPLE='\033[0;35m'  # 紫色 - 用于标题和重要分隔符显示
CYAN='\033[0;36m'    # 青色 - 用于模块标题和分组信息显示
NC='\033[0m'         # 无颜色 - 重置颜色设置，恢复终端默认颜色

# ============================================
# 配置变量 - 定义脚本运行的基础路径和文件
# Configuration variables - Define basic paths and files for script execution
# 这些变量用于确定项目结构和各个组件的位置
# ============================================
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"  # 脚本目录 - 当前脚本所在的绝对路径
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"                      # 项目根目录 - Ansible项目的根目录路径
SECURITY_SCRIPT="$SCRIPT_DIR/verify-security.sh"           # 安全验证脚本路径 - 专门用于安全配置验证
BACKUP_SCRIPT="$SCRIPT_DIR/verify-backup.sh"               # 备份验证脚本路径 - 专门用于备份系统验证
LOG_FILE="/var/log/system-verification.log"                # 日志文件路径 - 系统验证过程的详细日志记录

# ============================================
# 模块计数器 - 用于统计各个验证模块的执行结果
# Module counters for tracking verification results
# 这些计数器帮助生成最终的验证报告和系统评分
# ============================================
TOTAL_MODULES=0      # 总模块数 - 记录执行的所有验证模块总数量
PASSED_MODULES=0     # 通过模块数 - 记录成功通过验证的模块数量
FAILED_MODULES=0     # 失败模块数 - 记录验证失败的模块数量（需要立即处理）
WARNING_MODULES=0    # 警告模块数 - 记录有警告的模块数量（建议处理但非关键）

# ============================================
# 彩色输出结果函数 (Colored Output Result Function)
# 功能：格式化输出验证结果并记录到日志文件
# Function to print colored output
# 参数说明 (Parameters):
#   $1: 状态类型 (status) - PASS/FAIL/WARN/INFO/HEADER
#       - PASS: 验证通过，无问题 (Verification passed, no issues)
#       - FAIL: 验证失败，需要立即处理 (Verification failed, needs immediate attention)
#       - WARN: 验证有警告，建议处理 (Verification has warnings, recommended to address)
#       - INFO: 信息性输出，仅供参考 (Informational output, for reference only)
#       - HEADER: 标题显示，用于分组 (Header display, used for grouping)
#   $2: 消息内容 (message content) - 简要说明验证的内容
# 
# 输出格式 (Output format):
#   - 使用不同颜色区分结果类型 (Use different colors to distinguish result types)
#   - 同时记录到日志文件便于后续分析 (Also log to file for later analysis)
# ============================================
print_result() {
    local status="$1"     # 检查状态 (Check status)
    local message="$2"    # 输出消息 (Output message)
    local timestamp="$(date '+%Y-%m-%d %H:%M:%S')"  # 时间戳 (Timestamp)
    
    # 根据状态类型进行不同的颜色显示和日志记录
    # Display with different colors based on status type and log to file
    case "$status" in
        "PASS")
            echo -e "${GREEN}[PASS]${NC} $message"  # 绿色显示通过 (Green for pass)
            echo "[$timestamp] [PASS] $message" >> "$LOG_FILE"
            ;;
        "FAIL")
            echo -e "${RED}[FAIL]${NC} $message"   # 红色显示失败 (Red for fail)
            echo "[$timestamp] [FAIL] $message" >> "$LOG_FILE"
            ;;
        "WARN")
            echo -e "${YELLOW}[WARN]${NC} $message" # 黄色显示警告 (Yellow for warning)
            echo "[$timestamp] [WARN] $message" >> "$LOG_FILE"
            ;;
        "INFO")
            echo -e "${BLUE}[INFO]${NC} $message"  # 蓝色显示信息 (Blue for info)
            echo "[$timestamp] [INFO] $message" >> "$LOG_FILE"
            ;;
        "HEADER")
            echo -e "${PURPLE}[====]${NC} $message" # 紫色显示标题 (Purple for header)
            echo "[$timestamp] [HEADER] $message" >> "$LOG_FILE"
            ;;
    esac
}

# ============================================
# 模块验证执行函数 (Module Verification Execution Function)
# 功能：执行指定的验证模块脚本并处理其返回结果
# Function to run module verification
# 参数说明 (Parameters):
#   $1: 模块名称 (module_name) - 用于显示和日志记录的模块标识
#   $2: 脚本路径 (script_path) - 要执行的验证脚本的完整路径
#   $3: 描述信息 (description) - 模块的详细描述信息
# 
# 执行流程 (Execution flow):
#   1. 检查脚本文件是否存在 (Check if script file exists)
#   2. 验证脚本是否具有执行权限 (Verify script has execute permissions)
#   3. 执行验证脚本并捕获退出码 (Execute script and capture exit code)
#   4. 根据退出码更新相应的计数器 (Update counters based on exit code)
# 
# 退出码处理 (Exit code handling):
#   0 - 验证通过，所有检查都成功 (Verification passed, all checks successful)
#   1 - 验证失败，存在需要立即处理的问题 (Verification failed, critical issues)
#   2 - 验证有警告，存在建议处理的问题 (Verification has warnings)
#   其他 - 异常退出，脚本执行出现错误 (Abnormal exit, script execution error)
# ============================================
run_module_verification() {
    local module_name="$1"   # 模块名称 (Module name)
    local script_path="$2"   # 验证脚本路径 (Verification script path)
    local description="$3"   # 模块描述 (Module description)
    
    TOTAL_MODULES=$((TOTAL_MODULES + 1))  # 增加总模块计数 (Increment total module count)
    
    # 显示模块标题和描述信息
    # Display module header and description
    echo -e "\n${CYAN}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${CYAN}║ $description${NC}"
    echo -e "${CYAN}╚══════════════════════════════════════════════════════════════╝${NC}"
    
    # 检查验证脚本是否存在
    # Check if verification script exists
    if [ ! -f "$script_path" ]; then
        print_result "FAIL" "$module_name verification script not found: $script_path"
        FAILED_MODULES=$((FAILED_MODULES + 1))
        return 1
    fi
    
    # 检查验证脚本是否可执行
    # Check if verification script is executable
    if [ ! -x "$script_path" ]; then
        print_result "FAIL" "$module_name verification script not executable: $script_path"
        FAILED_MODULES=$((FAILED_MODULES + 1))
        return 1
    fi
    
    # 运行验证脚本并捕获退出码
    # Run the verification script and capture exit code
    local exit_code=0
    "$script_path" || exit_code=$?
    
    # 根据退出码处理结果并更新计数器
    # Process results based on exit code and update counters
    case $exit_code in
        0)
            print_result "PASS" "$module_name verification completed successfully"
            PASSED_MODULES=$((PASSED_MODULES + 1))
            ;;
        1)
            print_result "FAIL" "$module_name verification failed with critical errors"
            FAILED_MODULES=$((FAILED_MODULES + 1))
            ;;
        2)
            print_result "WARN" "$module_name verification completed with warnings"
            WARNING_MODULES=$((WARNING_MODULES + 1))
            ;;
        *)
            print_result "FAIL" "$module_name verification failed with exit code: $exit_code"
            FAILED_MODULES=$((FAILED_MODULES + 1))
            ;;
    esac
    
    return $exit_code
}

# Ansible项目结构检查函数
# Function to check Ansible project structure
# 功能说明 (Function description):
#   检查Ansible项目的目录结构和必需文件，确保项目结构完整
#   Checks Ansible project directory structure and required files to ensure project integrity
# 检查内容 (Check contents):
#   - 必需的配置文件和playbook文件 (Required config and playbook files)
#   - 角色目录结构和子目录 (Role directory structure and subdirectories)
#   - 角色的main.yml文件 (Role main.yml files)
#   - 脚本目录和脚本文件 (Scripts directory and script files)
# 预期结果 (Expected results):
#   - 所有必需文件都存在 (All required files exist)
#   - 角色目录结构完整 (Role directory structure is complete)
#   - 脚本目录包含验证脚本 (Scripts directory contains verification scripts)
check_ansible_project() {
    echo -e "\n${CYAN}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${CYAN}║ ANSIBLE PROJECT STRUCTURE VERIFICATION${NC}"
    echo -e "${CYAN}╚══════════════════════════════════════════════════════════════╝${NC}"
    
    # 检查主要项目文件
    # Check main project files
    # 定义必需的项目文件列表，这些文件是Ansible项目正常运行的基础
    # Define required project files list, these files are essential for Ansible project operation
    local required_files=(
        "ansible.cfg"          # Ansible配置文件 (Ansible configuration file)
        "inventory/hosts.yml"   # 主机清单文件 (Host inventory file)
        "group_vars/all.yml"   # 全局变量文件 (Global variables file)
        "site.yml"             # 主playbook文件 (Main playbook file)
        "security-setup.yml"   # 安全设置playbook (Security setup playbook)
        "backup-restore.yml"   # 备份恢复playbook (Backup restore playbook)
    )
    
    # 遍历检查必需文件
    # Loop through and check required files
    # 逐一检查每个必需文件是否存在，确保项目结构完整
    # Check each required file one by one to ensure project structure integrity
    for file in "${required_files[@]}"; do
        local file_path="$PROJECT_DIR/$file"
        if [ -f "$file_path" ]; then
            print_result "PASS" "Required file exists: $file"
        else
            print_result "FAIL" "Required file missing: $file"
        fi
    done
    
    # 检查角色目录结构
    # Check roles directory structure
    # 定义需要检查的角色列表，这些角色是系统的核心组件
    # Define roles list to check, these roles are core system components
    local roles=("security" "backup")
    # 遍历检查每个角色目录
    # Loop through and check each role directory
    # 检查每个角色的目录结构和必需文件
    # Check directory structure and required files for each role
    for role in "${roles[@]}"; do
        local role_dir="$PROJECT_DIR/roles/$role"
        if [ -d "$role_dir" ]; then
            print_result "PASS" "Role directory exists: $role"
            
            # 检查角色子目录
            # Check role subdirectories
            local role_subdirs=("tasks" "handlers" "templates" "defaults" "meta")
            for subdir in "${role_subdirs[@]}"; do
                local subdir_path="$role_dir/$subdir"
                if [ -d "$subdir_path" ]; then
                    print_result "PASS" "Role $role has $subdir directory"
                else
                    print_result "WARN" "Role $role missing $subdir directory"
                fi
            done
            
            # 检查main.yml文件
            # Check main.yml files
            local main_files=("tasks/main.yml" "handlers/main.yml" "defaults/main.yml" "meta/main.yml")
            for main_file in "${main_files[@]}"; do
                local main_file_path="$role_dir/$main_file"
                if [ -f "$main_file_path" ]; then
                    print_result "PASS" "Role $role has $main_file"
                else
                    print_result "WARN" "Role $role missing $main_file"
                fi
            done
        else
            print_result "FAIL" "Role directory missing: $role"
        fi
    done
    
    # Check scripts directory
    if [ -d "$SCRIPT_DIR" ]; then
        print_result "PASS" "Scripts directory exists"
        
        local script_count=$(find "$SCRIPT_DIR" -name "*.sh" | wc -l)
        print_result "INFO" "Found $script_count shell scripts"
    else
        print_result "FAIL" "Scripts directory missing"
    fi
}

# 系统先决条件检查函数
# Function to check system prerequisites
# 功能说明 (Function description):
#   检查运行环境和必需的系统工具，确保系统满足Ansible运行要求
#   Checks runtime environment and required system tools to ensure system meets Ansible requirements
# 检查内容 (Check contents):
#   - 用户权限检查 (User privilege check)
#   - 必需命令工具检查 (Required command tools check)
#   - 可选命令工具检查 (Optional command tools check)
#   - 系统服务状态检查 (System service status check)
#   - 磁盘和内存使用情况检查 (Disk and memory usage check)
# 预期结果 (Expected results):
#   - 具有足够的系统权限 (Have sufficient system privileges)
#   - 所有必需工具都已安装 (All required tools are installed)
#   - 系统资源使用在合理范围内 (System resource usage is within reasonable range)
check_system_prerequisites() {
    echo -e "\n${CYAN}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${CYAN}║ SYSTEM PREREQUISITES VERIFICATION${NC}"
    echo -e "${CYAN}╚══════════════════════════════════════════════════════════════╝${NC}"
    
    # 检查是否以root权限或sudo权限运行
    # Check if running as root or with sudo
    # 验证脚本是否具有足够的权限执行系统管理任务
    # Verify if script has sufficient privileges to perform system administration tasks
    if [ "$EUID" -eq 0 ]; then
        print_result "PASS" "Running with root privileges"
    else
        if sudo -n true 2>/dev/null; then
            print_result "PASS" "Running with sudo privileges"
        else
            print_result "WARN" "Not running with elevated privileges"
        fi
    fi
    
    # 检查必需的命令工具
    # Check required commands
    # 检查Ansible和系统管理所需的核心命令工具
    # Check core command tools required for Ansible and system management
    local required_commands=("ansible" "ansible-playbook" "systemctl" "crontab" "tar" "gzip" "openssl")
    for cmd in "${required_commands[@]}"; do
        if command -v "$cmd" >/dev/null 2>&1; then
            local version=$("$cmd" --version 2>/dev/null | head -1 || echo "unknown")
            print_result "PASS" "Command available: $cmd ($version)"
        else
            print_result "FAIL" "Required command not found: $cmd"
        fi
    done
    
    # 检查可选的命令工具
    # Check optional commands
    # 检查可选的命令工具，这些工具可能在特定场景下需要
    # Check optional command tools that may be needed in specific scenarios
    local optional_commands=("gpg" "rsync" "aws" "mysql" "mysqldump" "pg_dump" "psql")
    for cmd in "${optional_commands[@]}"; do
        if command -v "$cmd" >/dev/null 2>&1; then
            print_result "PASS" "Optional command available: $cmd"
        else
            print_result "INFO" "Optional command not found: $cmd"
        fi
    done
    
    # 检查系统服务状态
    # Check system services
    local services=("systemd" "cron")
    for service in "${services[@]}"; do
        if systemctl is-active --quiet "$service" 2>/dev/null || systemctl is-active --quiet "${service}d" 2>/dev/null; then
            print_result "PASS" "System service running: $service"
        else
            print_result "WARN" "System service not running: $service"
        fi
    done
    
    # 检查磁盘空间使用情况
    # Check disk space
    local root_usage=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
    if [ $root_usage -lt 80 ]; then
        print_result "PASS" "Root filesystem usage: ${root_usage}%"
    elif [ $root_usage -lt 90 ]; then
        print_result "WARN" "Root filesystem usage: ${root_usage}%"
    else
        print_result "FAIL" "Root filesystem usage: ${root_usage}% - CRITICAL"
    fi
    
    # 检查内存使用情况
    # Check memory
    local mem_total=$(free -m | awk 'NR==2{print $2}')
    local mem_used=$(free -m | awk 'NR==2{print $3}')
    local mem_usage=$((mem_used * 100 / mem_total))
    
    if [ $mem_usage -lt 80 ]; then
        print_result "PASS" "Memory usage: ${mem_usage}% (${mem_used}M/${mem_total}M)"
    elif [ $mem_usage -lt 90 ]; then
        print_result "WARN" "Memory usage: ${mem_usage}% (${mem_used}M/${mem_total}M)"
    else
        print_result "FAIL" "Memory usage: ${mem_usage}% (${mem_used}M/${mem_total}M) - HIGH"
    fi
}

# Ansible连接测试函数
# Function to test Ansible connectivity
# 功能说明 (Function description):
#   测试Ansible与目标主机的连接性和playbook语法，确保Ansible配置正确
#   Tests Ansible connectivity to target hosts and playbook syntax to ensure Ansible configuration is correct
# 检查内容 (Check contents):
#   - 清单文件存在性检查 (Inventory file existence check)
#   - Ansible ping连接测试 (Ansible ping connectivity test)
#   - 主要playbook语法检查 (Main playbook syntax check)
#   - 安全和备份playbook语法检查 (Security and backup playbook syntax check)
# 预期结果 (Expected results):
#   - 清单文件存在且格式正确 (Inventory file exists and format is correct)
#   - 能够连接到目标主机 (Can connect to target hosts)
#   - 所有playbook语法都正确 (All playbook syntax is correct)
test_ansible_connectivity() {
    echo -e "\n${CYAN}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${CYAN}║ ANSIBLE CONNECTIVITY TEST${NC}"
    echo -e "${CYAN}╚══════════════════════════════════════════════════════════════╝${NC}"
    
    local inventory_file="$PROJECT_DIR/inventory/hosts.yml"  # 清单文件路径 (Inventory file path)
    
    # 检查清单文件是否存在
    # Check if inventory file exists
    # 验证Ansible清单文件是否存在，这是连接测试的前提
    # Verify if Ansible inventory file exists, which is prerequisite for connectivity test
    if [ -f "$inventory_file" ]; then
        print_result "PASS" "Inventory file found: $inventory_file"
        
        # 切换到项目目录
        # Change to project directory
        cd "$PROJECT_DIR" || exit 1
        
        # 测试ansible ping连接
        # Test ansible ping
        if ansible all -m ping >/dev/null 2>&1; then
            print_result "PASS" "Ansible ping successful to all hosts"
        else
            print_result "WARN" "Ansible ping failed (may be expected for remote hosts)"
        fi
        
        # 测试主playbook语法
        # Test main playbook syntax
        if ansible-playbook --syntax-check site.yml >/dev/null 2>&1; then
            print_result "PASS" "Main playbook syntax is valid"
        else
            print_result "FAIL" "Main playbook has syntax errors"
        fi
        
        # 测试安全playbook语法
        # Test security playbook syntax
        if ansible-playbook --syntax-check security-setup.yml >/dev/null 2>&1; then
            print_result "PASS" "Security playbook syntax is valid"
        else
            print_result "FAIL" "Security playbook has syntax errors"
        fi
        
        # 测试备份playbook语法
        # Test backup playbook syntax
        if ansible-playbook --syntax-check backup-restore.yml >/dev/null 2>&1; then
            print_result "PASS" "Backup playbook syntax is valid"
        else
            print_result "FAIL" "Backup playbook has syntax errors"
        fi
    else
        print_result "FAIL" "Inventory file not found: $inventory_file"
    fi
}

# 系统报告生成函数
# Function to generate system report
# 功能说明 (Function description):
#   生成详细的系统验证报告，包含验证结果和系统信息
#   Generates detailed system verification report with verification results and system info
# 报告内容 (Report contents):
#   - 验证结果摘要 (Verification results summary)
#   - 系统基本信息 (System basic information)
#   - 已安装软件包信息 (Installed packages information)
#   - 日志摘录 (Log excerpt)
# 输出位置 (Output location):
#   - 报告文件保存在/tmp目录下 (Report file saved in /tmp directory)
#   - 文件名包含时间戳便于识别 (Filename includes timestamp for identification)
generate_system_report() {
    # 生成带时间戳的报告文件路径
    # Generate timestamped report file path
    # 创建唯一的报告文件名，避免文件名冲突
    # Create unique report filename to avoid filename conflicts
    local report_file="/tmp/system-verification-report-$(date +%Y%m%d-%H%M%S).txt"
    
    # 写入报告标题和基本信息
    # Write report header and basic information
    # 记录报告生成的基本信息，包括时间、主机名和用户
    # Record basic information about report generation, including time, hostname and user
    echo "System Verification Report" > "$report_file"
    echo "Generated: $(date)" >> "$report_file"
    echo "Hostname: $(hostname)" >> "$report_file"
    echo "User: $(whoami)" >> "$report_file"
    echo "" >> "$report_file"
    
    # 写入验证结果摘要
    # Write verification results summary
    echo "=== SUMMARY ===" >> "$report_file"
    echo "Total modules checked: $TOTAL_MODULES" >> "$report_file"
    echo "Passed: $PASSED_MODULES" >> "$report_file"
    echo "Failed: $FAILED_MODULES" >> "$report_file"
    echo "Warnings: $WARNING_MODULES" >> "$report_file"
    echo "" >> "$report_file"
    
    # 写入系统信息
    # Write system information
    echo "=== SYSTEM INFO ===" >> "$report_file"
    echo "OS: $(cat /etc/os-release | grep PRETTY_NAME | cut -d'=' -f2 | tr -d '"')" >> "$report_file"
    echo "Kernel: $(uname -r)" >> "$report_file"
    echo "Uptime: $(uptime)" >> "$report_file"
    echo "" >> "$report_file"
    
    # 写入已安装软件包信息
    # Write installed packages information
    echo "=== INSTALLED PACKAGES ===" >> "$report_file"
    if command -v rpm >/dev/null 2>&1; then
        echo "Ansible: $(rpm -q ansible 2>/dev/null || echo 'not installed via RPM')" >> "$report_file"
    elif command -v dpkg >/dev/null 2>&1; then
        echo "Ansible: $(dpkg -l | grep ansible | head -1 || echo 'not installed via DEB')" >> "$report_file"
    fi
    
    # 写入日志摘录
    # Write log excerpt
    echo "" >> "$report_file"
    echo "=== LOG EXCERPT ===" >> "$report_file"
    if [ -f "$LOG_FILE" ]; then
        tail -50 "$LOG_FILE" >> "$report_file"
    fi
    
    # 输出报告生成成功信息
    # Output report generation success message
    print_result "INFO" "System report generated: $report_file"
}

# 最终摘要显示函数
# Function to display final summary
# 功能说明 (Function description):
#   显示验证结果的最终摘要和系统状态，提供系统健康度评估
#   Displays final summary of verification results and system status, provides system health assessment
# 显示内容 (Display contents):
#   - 模块验证结果统计 (Module verification results statistics)
#   - 总体评分计算 (Overall score calculation)
#   - 系统状态评估 (System status assessment)
#   - 下一步操作建议 (Next steps recommendations)
#   - 快速命令参考 (Quick commands reference)
#   - 文档链接 (Documentation links)
# 评估标准 (Assessment criteria):
#   - 优秀：无失败无警告 (Excellent: no failures, no warnings)
#   - 良好：无失败但有警告 (Good: no failures but warnings)
#   - 一般：少量失败 (Fair: few failures)
#   - 差：多个关键问题 (Poor: multiple critical issues)
display_final_summary() {
    echo -e "\n${PURPLE}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${PURPLE}║                    VERIFICATION SUMMARY                     ║${NC}"
    echo -e "${PURPLE}╚══════════════════════════════════════════════════════════════╝${NC}"
    
    # 显示模块验证结果
    # Display module verification results
    # 统计并显示各个模块的验证结果，提供清晰的数据概览
    # Count and display verification results for each module, providing clear data overview
    echo -e "\n${BLUE}Module Results:${NC}"
    echo -e "Total modules: $TOTAL_MODULES"  # 总模块数 (Total modules)
    echo -e "${GREEN}Passed: $PASSED_MODULES${NC}"  # 通过的模块数 (Passed modules)
    echo -e "${RED}Failed: $FAILED_MODULES${NC}"  # 失败的模块数 (Failed modules)
    echo -e "${YELLOW}Warnings: $WARNING_MODULES${NC}"  # 警告的模块数 (Warning modules)
    
    # 计算并显示总体评分
    # Calculate and display overall score
    if [ $TOTAL_MODULES -gt 0 ]; then
        local score=$((PASSED_MODULES * 100 / TOTAL_MODULES))  # 计算通过率
        echo -e "\nOverall Score: $score%"  # 显示总体评分
    fi
    
    # 显示系统状态评估
    # Display system status assessment
    echo -e "\n${BLUE}System Status:${NC}"
    if [ $FAILED_MODULES -eq 0 ] && [ $WARNING_MODULES -eq 0 ]; then
        echo -e "${GREEN}✓ EXCELLENT! All system checks passed.${NC}"  # 优秀！所有系统检查都通过
        echo -e "${GREEN}  Your Ansible infrastructure is properly configured.${NC}"  # 您的Ansible基础设施配置正确
    elif [ $FAILED_MODULES -eq 0 ]; then
        echo -e "${YELLOW}⚠ GOOD! No critical failures, but some warnings to address.${NC}"  # 良好！无关键故障，但有一些警告需要处理
        echo -e "${YELLOW}  Review the warnings and consider improvements.${NC}"  # 检查警告并考虑改进
    elif [ $FAILED_MODULES -le 2 ]; then
        echo -e "${YELLOW}⚠ FAIR! Some issues detected that need attention.${NC}"  # 一般！检测到一些需要关注的问题
        echo -e "${YELLOW}  Address the failed checks before production use.${NC}"  # 在生产使用前解决失败的检查
    else
        echo -e "${RED}✗ POOR! Multiple critical issues detected.${NC}"  # 差！检测到多个关键问题
        echo -e "${RED}  Significant configuration problems need immediate attention.${NC}"  # 重大配置问题需要立即关注
    fi
    
    # 提供下一步操作建议
    # Provide next steps recommendations
    echo -e "\n${BLUE}Next Steps:${NC}"
    if [ $FAILED_MODULES -gt 0 ]; then
        echo -e "1. Review and fix all failed checks"  # 检查并修复所有失败的检查
        echo -e "2. Re-run verification: $0"  # 重新运行验证
        echo -e "3. Check individual module scripts for details"  # 检查各个模块脚本的详细信息
    else
        echo -e "1. Deploy configurations: ansible-playbook site.yml"  # 部署配置
        echo -e "2. Monitor system status regularly"  # 定期监控系统状态
        echo -e "3. Keep configurations updated"  # 保持配置更新
    fi
    
    echo -e "\n${BLUE}Quick Commands:${NC}"
    echo -e "Security check:    $SECURITY_SCRIPT"
    echo -e "Backup check:      $BACKUP_SCRIPT"
    echo -e "Full verification: $0"
    echo -e "View logs:         tail -f $LOG_FILE"
    
    echo -e "\n${BLUE}Documentation:${NC}"
    echo -e "Project README:    $PROJECT_DIR/README.md"
    echo -e "Security docs:     $PROJECT_DIR/roles/security/README.md"
    echo -e "Backup docs:       $PROJECT_DIR/roles/backup/README.md"
}

# ============================================
# 主执行流程 (Main Execution Flow)
# ============================================
# 功能说明 (Function description):
#   系统验证脚本的主要执行流程，按顺序运行所有验证检查
#   Main execution flow of system verification script, runs all verification checks in sequence
# 执行步骤 (Execution steps):
#   1. 显示脚本标题和启动时间 (Display script title and start time)
#   2. 初始化日志文件 (Initialize log file)
#   3. 运行系统先决条件检查 (Run system prerequisites check)
#   4. 运行Ansible项目结构检查 (Run Ansible project structure check)
#   5. 运行Ansible连接测试 (Run Ansible connectivity test)
#   6. 运行各个模块验证 (Run individual module verifications)
#   7. 生成报告和显示摘要 (Generate report and display summary)
#   8. 根据结果退出 (Exit based on results)
# ============================================

echo -e "${PURPLE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${PURPLE}║                 SYSTEM VERIFICATION SCRIPT                  ║${NC}"
echo -e "${PURPLE}║                    $(date '+%Y-%m-%d %H:%M:%S')                     ║${NC}"
echo -e "${PURPLE}╚══════════════════════════════════════════════════════════════╝${NC}"

# 初始化日志文件
# Initialize log file
# 创建日志目录并初始化日志文件，记录验证过程
# Create log directory and initialize log file to record verification process
mkdir -p "$(dirname "$LOG_FILE")"
echo "=== System Verification Started: $(date) ===" >> "$LOG_FILE"

# 运行所有验证模块
# Run all verification modules
# 按顺序执行系统级别的验证检查
# Execute system-level verification checks in sequence
check_system_prerequisites
check_ansible_project
test_ansible_connectivity

# 运行各个模块验证
# Run individual module verifications
# 调用专门的验证脚本检查各个功能模块
# Call specialized verification scripts to check each functional module
run_module_verification "Security" "$SECURITY_SCRIPT" "SECURITY CONFIGURATION VERIFICATION"
run_module_verification "Backup" "$BACKUP_SCRIPT" "BACKUP SYSTEM VERIFICATION"

# 生成报告并显示摘要
# Generate report and display summary
# 生成详细的验证报告文件并显示最终摘要
# Generate detailed verification report file and display final summary
generate_system_report
display_final_summary

# 记录完成日志
# Log completion
# 在日志文件中记录验证完成时间
# Record verification completion time in log file
echo "=== System Verification Completed: $(date) ===" >> "$LOG_FILE"

# 根据验证结果退出
# Exit with appropriate code
# 根据验证结果设置适当的退出码，便于自动化脚本判断
# Set appropriate exit code based on verification results for automation script judgment
if [ $FAILED_MODULES -gt 0 ]; then
    exit 1  # 有失败的模块 (Has failed modules)
elif [ $WARNING_MODULES -gt 0 ]; then
    exit 2  # 有警告的模块 (Has warning modules)
else
    exit 0  # 所有检查都通过 (All checks passed)
fi